/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.star.admin.controller;

import com.star.common.ActionType;
import com.star.common.CommonUtil;
import com.star.common.ConfigFactory;
import com.star.common.NewsCateData;
import com.star.common.PostData;
import com.star.common.ProfileData;
import com.star.common.Re_Post_NewsCate_Data;
import com.star.common.Re_Post_Profile_Data;
import com.star.common.RenderModel;
import com.star.common.UserData;
import com.star.common.UserRole;
import com.start.model.ActionModel;
import com.start.model.NewsCateModel;
import com.start.model.PostModel;
import com.start.model.ProfileModel;
import com.start.model.Re_Post_NewsCate_Model;
import com.start.model.Re_Post_Profile_Model;
import com.start.model.SessionModel;
import com.start.model.UserModel;
import hapax.Template;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javaxt.io.Image;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

/**
 *
 * @author ngotandieu
 */
public class AdminPostController extends HttpServlet {

    private static final Logger logger = Logger.getLogger(AdminPostController.class);
    private static final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    private static final int POST_PER_PAGE = 30;
    public static final String STATIC_UPLOAD_IMAGE = ConfigFactory.getParam("upload", "upload_path") + ConfigFactory.getParam("upload", "upload_image");
    public static final String STATIC_UPLOAD_VIDEO = ConfigFactory.getParam("upload", "upload_path") + ConfigFactory.getParam("upload", "upload_video");
    public static final String STATIC_URL_IMAGE = ConfigFactory.getParam("static", "img") + ConfigFactory.getParam("upload", "upload_image");
    public static final String STATIC_URL_VIDEO = ConfigFactory.getParam("static", "img") + ConfigFactory.getParam("upload", "upload_video");

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    private void handle(HttpServletRequest req, HttpServletResponse resp) {
        try {
            if (!CommonUtil.checkSession(req, resp)) {
                return;
            }
            processs(req, resp);
        } catch (IOException ex) {
            logger.error("AdminPostController.handle:" + ex.getMessage(), ex);
        }
    }

    private void processs(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content;
        String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo();
        switch (pathInfo) {
            case "/edit":
                content = renderEditPage(req, resp);
                break;
            case "/ajax-edit":
                content = ajaxEdit(req, resp);
                break;
            case "/add":
                content = renderAddPage(req, resp);
                break;
            case "/ajax-add":
                content = ajaxAdd(req, resp);
                break;
            case "/ajax-delete":
                content = ajaxDelete(req, resp);
                break;
            case "/list/search":
                content = renderSearchPage(req, resp);
                break;  
            case "/list":
                content = renderListPage(req, resp);
                break;
            case "/ajax-upload-image":
                content = ajaxUploadImage(req, resp);
                break;
            default:
                content = renderListPage(req, resp);
                //content = renderIndexPage(req, resp);
        }
        CommonUtil.out(content, resp);
    }

//    private String renderIndexPage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//        String content = "";
//        try {
//            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
//            if (!CommonUtil.checkAccess(req, UserRole.POST)) {
//                resp.sendRedirect("/");
//                return "";
//            }
//
//            String pId = req.getParameter("pid") != null ? req.getParameter("pid") : "";
//            if (pId.isEmpty()) {
//                resp.sendRedirect("/profile/post");
//                return "";
//            }
//
//            TemplateDataDictionary dic = TemplateDictionary.create();
//            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
//            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
//            dic.setVariable("MENU", CommonUtil.getAdminMenu(req));
//            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "post_list"));
//            dic.setVariable("PAGE_TITLE", "Danh sách tin tức");
//
//            int page = 1;
//            String p = req.getParameter("p") == null ? "1" : req.getParameter("p");
//            try {
//                page = Integer.parseInt(p);
//            } catch (NumberFormatException e) {
//            }
//
//            PostModel appsModel = PostModel.getInstance();
//            List<PostData> lstPost = appsModel.getPost(pId, (page - 1) * POST_PER_PAGE, POST_PER_PAGE);
//            if (lstPost != null) {
//                for (PostData postData : lstPost) {
//                    TemplateDataDictionary section = dic.addSection("LIST_POST");
//                    section.setVariable("POST_ID", String.valueOf(postData.getId()));
//                    section.setVariable("POST_TITLE", postData.getTitle());
//                    section.setVariable("POST_DESC", postData.getDesc());
//
//                    String updated = formatter.format(postData.getUpdated() * 1000L);
//                    section.setVariable("UPDATED", updated);
//                    if (postData.getStatus() == 1) {
//                        section.showSection("ACTIVE_YES");
//                    } else {
//                        section.showSection("ACTIVE_NO");
//                    }
//                }
//            }
//            int count = (int) appsModel.getPostCount(pId);
//            String pageNavi = CommonUtil.getPageNavi(page, count, POST_PER_PAGE, "");
//            dic.setVariable("PAGENAVI", pageNavi);
//
//            Template template = RenderModel.getAdminCTemplate("post_list");
//            content = template.renderToString(dic);
//        } catch (Exception ex) {
//            logger.error("AppsController.renderIndexPage: " + ex.getMessage(), ex);
//        }
//        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
//        return content;
//    }

    private String renderAddPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
            if (!CommonUtil.checkAccess(req, UserRole.POST_ADD)) {
                resp.sendRedirect("/");
                return "";
            }
            String pId = req.getParameter("pid") != null ? req.getParameter("pid") : "";
//            if (pId.isEmpty()) {
//                resp.sendRedirect("/profile/post");
//                return "";
//            }

            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req));
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "postadd"));
            dic.setVariable("PAGE_TITLE", "Thêm mới tin tức");
            ProfileModel profileModel = ProfileModel.getInstance();
            if(!pId.equals(""))
            {
                dic.showSection("PROFILE_BACK");
                dic.setVariable("POST_PID", pId);                
                ProfileData profileData = profileModel.getProfileById(pId);                
                TemplateDataDictionary section = dic.addSection("PROFILE_SELECTED");
                section.setVariable("PROFILE_ID", String.valueOf(profileData.getId()));
                section.setVariable("PROFILE_NAME", profileData.getName());
            }
            if (CommonUtil.checkAccess(req, UserRole.POST_PUBLIC)) {
                dic.showSection("OP_PUBLISH");
            }
            dic.showSection("NO_THUMB");
            NewsCateModel newsCateModel = NewsCateModel.getInstance();
            List<NewsCateData> listNewsCate = newsCateModel.getCate(0, -1);
            if (listNewsCate != null && !listNewsCate.isEmpty()) {
                for (NewsCateData cateData : listNewsCate) {
                    TemplateDataDictionary section = dic.addSection("NEWSCATE_LIST");
                    section.setVariable("NEWSCATE_ID", String.valueOf(cateData.getId()));
                    section.setVariable("NEWSCATE_NAME", cateData.getName());
                }
            }  
            dic.showSection("ADD_PAGE");                   
            dic.setVariable("PROFILE_LIST", profileModel.getProfileList());
            Template template = RenderModel.getAdminCTemplate("post_add");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("AdminPostController.renderAddPage: " + ex.getMessage(), ex);
        }
        return content;
    }

    
    private String ajaxAdd(HttpServletRequest req, HttpServletResponse resp) {
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
        if (!CommonUtil.checkAccess(req, UserRole.POST_ADD)) {
            return CommonUtil.toPermissionDenied();
        }

        String content;
        int error = 0;
        String msg = "Thêm Tin tức thành công.";
        Map<String, String> data = new HashMap<>();
        try {            
            String title = "";
            String slug = CommonUtil.URLFriendly(title);
            String desc = "";
            String scontent = "";
            long published = 0;
            String status = "0";                            
            String site = "";
            String image = "";
            FileItem fileImage = null;
            List<String> lstProfile = new ArrayList<>();
            List<String> lstCats = new ArrayList<>();     
            String pid = "";
            
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(repository);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(req);
            Iterator<FileItem> iter = items.iterator();
            Date dateNow = new Date(); 
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            while (iter.hasNext()) {
                FileItem item = iter.next();
                String name = item.getFieldName();
                if (item.isFormField()) {
                    String value = item.getString("UTF-8");
                    switch (name) {
                        case "postTitle":
                            title = value;
                            break;
                        case "postTime":
                            if (!value.isEmpty()) {
                                //Date date = formatter.parse(value);
                                if(value.length() == 10)
                                    value = value + " 00:00";
                                Date date = sdf.parse(value);
                                published = date.getTime();
                            } else {
                                published = System.currentTimeMillis();
                            }
                            break;
                        case "postStatus":
                            status = value;
                            break;
                        case "postSource":
                            site = value;
                            break; 
                        case "newsCate":
                            lstCats.add(value);
                            break;                        
                        case "postDesc":
                            desc = value;
                            break;
                        case "postContent":
                            scontent = value;
                            break;
                        case "postListProfile":
                            lstProfile = Arrays.asList(value.split("\\s*,\\s*"));
                            break;
                        case "postPid":
                            pid = value;
                            break;
                    }
                } else {
                    if (name.equalsIgnoreCase("newsImage")) {
                        String fileName = item.getName();
                        String contentType = item.getContentType();
                        if (!contentType.startsWith("image/")) {
                            msg = "Chỉ được phép upload hình jpg, png, gif.";
                            error = -1;
                        }
                        long sizeInBytes = item.getSize();
                        if (sizeInBytes > 1024 * 1000) {
                            msg = "Kích thước tối đa 1 MB.";
                            error = -1;
                        }
                        image = (System.currentTimeMillis() / 1000) + "_" + fileName.toLowerCase();
                        image = image.substring(0, image.length() - 4) + ".jpg";
                        fileImage = item;
                    }
                }
            }            
                 
            if (title.equalsIgnoreCase("")) {
                msg = "Tiêu đề tin tức không được trống.";
                error = -1;
            }
            if(lstCats.isEmpty()){
                msg = "Chưa chọn danh mục.";
                error = -1;
            }
            
            if (error == 0) {
                SessionModel sessionModel = SessionModel.getInstance();
                String author = sessionModel.getUserLogin(req);
                PostModel postModel = PostModel.getInstance();
                PostData postData = new PostData(title, slug, desc, scontent, author, 
                        Short.parseShort(status), published, site, image, "", "");
                String postId = postModel.addNewPost(postData);                
                if (!postId.isEmpty()) {
                    for (String cate : lstCats) {
                        Re_Post_NewsCate_Data dataRe = new Re_Post_NewsCate_Data(postId, cate);
                        Re_Post_NewsCate_Model modelRe = Re_Post_NewsCate_Model.getInstance();
                        modelRe.addItems(dataRe);
                    }
                    
                    ProfileModel profileModel = ProfileModel.getInstance();
                    Re_Post_Profile_Model modelRe = Re_Post_Profile_Model.getInstance();
                    for(String idProfile : lstProfile){
                        if(!idProfile.equals("")){
                            ProfileData profileData = profileModel.getProfileById(idProfile);
                            if(profileData != null){
                                Re_Post_Profile_Data dataRe = new Re_Post_Profile_Data(postId, idProfile);                                
                                modelRe.addItems(dataRe);
                            }   
                        }                        
                    }
                    data.put("id", postId);
                    data.put("pid", pid);                    
                    String timeDir = (dateNow.getYear() + 1900) + "_" + (dateNow.getMonth() + 1);
                    saveThumb(fileImage, image, timeDir);
                    ActionModel actionModel = ActionModel.getInstance();                    
                    actionModel.addAction(req, author, ActionType.POST_ADD, postId, title);
                }
            }   
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg, data);
        return content;
    }

    
    
    private void saveThumb(FileItem fileImage, String image_pa, String timeDir) throws Exception {
        if (fileImage != null) {
            Image image = new Image(fileImage.get());
            image.resize(250, 250);
            int w = image.getWidth() > 250 ? 250 : image.getWidth();
            int h = image.getHeight() > 250 ? 250 : image.getHeight();
            image.crop(0, 0, w, h);

            BufferedImage bi = CommonUtil.convertPNGToJPG(image.getBufferedImage());
            String localPath = STATIC_UPLOAD_IMAGE + timeDir + "/" + image_pa;
            File uploadedFile = new File(localPath);
            uploadedFile.getParentFile().mkdirs();
            ImageIO.write(bi, "jpg", uploadedFile);
        }
    }
    
    
    
    private String renderListPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
            if (!CommonUtil.checkAccess(req, UserRole.POST_VIEW) && !CommonUtil.checkAccess(req, UserRole.POST_EDIT)) {
                resp.sendRedirect("/");
                return "";
            }

            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req)); 
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "postedit"));            
            dic.setVariable("PAGE_TITLE", "Danh sách tin tức profile");
                        
            int page = 1;
            String p = req.getParameter("p") == null ? "1" : req.getParameter("p");
            try {
                page = Integer.parseInt(p);
            } catch (NumberFormatException e) {
            }
                        
            PostModel postModel = PostModel.getInstance();
            ProfileModel profileModel = ProfileModel.getInstance();
            List<PostData> lstPostData = postModel.getPost((page - 1) * POST_PER_PAGE, POST_PER_PAGE); 
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Re_Post_Profile_Model reModel = Re_Post_Profile_Model.getInstance();
            if (lstPostData != null && !lstPostData.isEmpty()) {
                for (PostData postData : lstPostData) {                    
                    TemplateDataDictionary section = dic.addSection("LIST_POST");
                    section.setVariable("AUTHOR", String.valueOf(postData.getAuthor()));                    
                    section.setVariable("POST_ID", postData.getId());  
                    section.setVariable("POST_TITLE", postData.getTitle());  
                   
                    List<Re_Post_Profile_Data> items = reModel.getItemsByPostId(postData.getId());
                    for(Re_Post_Profile_Data dt : items){
                        ProfileData profileData = profileModel.getProfileById(dt.getIdProfile());
                        TemplateDataDictionary sectionProfile = section.addSection("PROFILE_LIST_RESULT");
                        sectionProfile.setVariable("PROFILE_ID_RESULT", String.valueOf(profileData.getId()));
                        sectionProfile.setVariable("PROFILE_NAME_RESULT", profileData.getName());
                    }
                    
                    Date d = new Date(postData.getCreated());
                    section.setVariable("CREATED", sdf.format(d));                    
                    if (postData.getStatus() == 0) { 
                        section.setVariable("STATUS", "Chờ duyệt");
                        section.showSection("WARNING");
                    }                   
                    else if(postData.getStatus() == 1){
                        section.setVariable("STATUS", "Công khai");
                    }
                    else{
                        section.setVariable("STATUS", "Ẩn");
                        section.showSection("DANGER");
                    }
                }
            }
            
            UserModel userModel = UserModel.getInstance();
            List<UserData> userList = userModel.getUser(0, -1);
            for (UserData userData : userList) {
                TemplateDataDictionary section = dic.addSection("USER_LIST");
                section.setVariable("USER_ID", userData.getId());
                section.setVariable("USER_NAME", userData.getUsername());                
            }
            
            List<ProfileData> listProfileData = profileModel.getProfile(0, -1);
            for(ProfileData profileData : listProfileData){
                TemplateDataDictionary section = dic.addSection("PROFILE_LIST");
                section.setVariable("PROFILE_ID", profileData.getId());
                section.setVariable("PROFILE_NAME", profileData.getName()); 
            }
            
            NewsCateModel newsCateModel = NewsCateModel.getInstance();
            List<NewsCateData> lstNewsCate = newsCateModel.getCate(0, -1);
            if (lstNewsCate != null && !lstNewsCate.isEmpty()) {
                for (NewsCateData newsCateData : lstNewsCate) {
                    TemplateDataDictionary section = dic.addSection("CATE_LIST");
                    section.setVariable("CATE_ID", String.valueOf(newsCateData.getId()));
                    section.setVariable("CATE_NAME", newsCateData.getName());
                }
            }
             
            int count = postModel.getPost(0, -1).size();
            String pageNavi = CommonUtil.getPageNavi(page, count, POST_PER_PAGE, "");
            dic.setVariable("PAGENAVI", pageNavi);
                        
            Template template = RenderModel.getAdminCTemplate("post_profile_list");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("AdminPostController.renderListPage: " + ex.getMessage(), ex);
        }
        return content;
    }
    
    
    
    private String renderSearchPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
            if (!CommonUtil.checkAccess(req, UserRole.POST_VIEW) && !CommonUtil.checkAccess(req, UserRole.POST_EDIT)) {
                return CommonUtil.toPermissionDenied();
            }

            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req)); 
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "postedit"));            
            dic.setVariable("PAGE_TITLE", "Danh sách tin tức profile");
                        
            int page = 1;
            String p = req.getParameter("p") == null ? "1" : req.getParameter("p");
            try {
                page = Integer.parseInt(p);
            } catch (NumberFormatException e) {
            }
            
            String id_Search = req.getParameter("postID") != null ? req.getParameter("postID") : "";
            String pid_Search = req.getParameter("postProfile") != null ? req.getParameter("postProfile") : "";
            String user = req.getParameter("postUser") != null ? req.getParameter("postUser") : "";
            String title = req.getParameter("postTitle") != null ? req.getParameter("postTitle") : "";   
            String cate = req.getParameter("postCate") != null ? req.getParameter("postCate") : "";
            String created = req.getParameter("postCreated") != null ? req.getParameter("postCreated") : "";
            String status = req.getParameter("postStatus") != null ? req.getParameter("postStatus") : "";              
            String userSearch = "";
            if(!user.equals("")){
                UserModel userModelSearch = UserModel.getInstance();
                UserData userDataSearch = userModelSearch.getUserById(user);
                userSearch = userDataSearch.getUsername();
            }
            
            PostModel postModel = PostModel.getInstance();
            List<PostData> lstPostData = postModel.getPost(0, -1, id_Search, pid_Search, 
                    userSearch, title, status, created, cate);  
            ProfileModel profileModel = ProfileModel.getInstance();
            NewsCateModel newsCateModel = NewsCateModel.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Re_Post_Profile_Model reModel = Re_Post_Profile_Model.getInstance();
            if (lstPostData != null && !lstPostData.isEmpty()) {                
                for(int i = (page - 1) * POST_PER_PAGE; i < page * POST_PER_PAGE; i++){ 
                    if(i == lstPostData.size())
                        break;
                    PostData postData = lstPostData.get(i);
                    TemplateDataDictionary section = dic.addSection("LIST_POST");
                    section.setVariable("AUTHOR", String.valueOf(postData.getAuthor()));                    
                    section.setVariable("POST_ID", postData.getId());  
                    section.setVariable("POST_TITLE", postData.getTitle());
                    
                    List<Re_Post_Profile_Data> items = reModel.getItemsByPostId(postData.getId());
                    for(Re_Post_Profile_Data dt : items){
                        ProfileData profileData = profileModel.getProfileById(dt.getIdProfile());
                        TemplateDataDictionary sectionProfile = section.addSection("PROFILE_LIST_RESULT");
                        sectionProfile.setVariable("PROFILE_ID_RESULT", String.valueOf(profileData.getId()));
                        sectionProfile.setVariable("PROFILE_NAME_RESULT", profileData.getName());
                    }
                    
                    Date d = new Date(postData.getCreated());
                    section.setVariable("CREATED", sdf.format(d));                   
                                  
                    if (postData.getStatus() == 0) { 
                        section.setVariable("STATUS", "Chờ duyệt");
                        section.showSection("WARNING");
                    }                   
                    else if(postData.getStatus() == 1){
                        section.setVariable("STATUS", "Công khai");
                    }
                    else{
                        section.setVariable("STATUS", "Ẩn");
                        section.showSection("DANGER");
                    }                   
                }
            }
                      
            dic.setVariable("ID_SEARCH", id_Search);
            List<ProfileData> listProfileData = profileModel.getProfile(0, -1);
            for(ProfileData profileData : listProfileData){
                TemplateDataDictionary section = dic.addSection("PROFILE_LIST");
                section.setVariable("PROFILE_ID", profileData.getId());
                section.setVariable("PROFILE_NAME", profileData.getName()); 
                if(pid_Search.equals(profileData.getId()))
                    section.showSection("PROFILE_SELECTED");
            }
            
            UserModel userModel = UserModel.getInstance();
            List<UserData> userList = userModel.getUser(0, -1);
            for (UserData userData : userList) {
                TemplateDataDictionary section = dic.addSection("USER_LIST");
                section.setVariable("USER_ID", userData.getId());
                section.setVariable("USER_NAME", userData.getUsername()); 
                if(user.equals(userData.getId()))
                    section.showSection("USER_SELECTED");
            }
            
            dic.setVariable("TITLE_SEARCH", title);
            List<NewsCateData> lstNewsCate = newsCateModel.getCate(0, -1);
            if (lstNewsCate != null && !lstNewsCate.isEmpty()) {
                for (NewsCateData newsCateData : lstNewsCate) {
                    TemplateDataDictionary section = dic.addSection("CATE_LIST");
                    section.setVariable("CATE_ID", String.valueOf(newsCateData.getId()));
                    section.setVariable("CATE_NAME", newsCateData.getName());
                    if(newsCateData.getId().equals(cate))
                        section.showSection("CATE_SELECTED");
                }
            }
            
            dic.setVariable("CREATE_SEARCH", created);        
                                     
            if (status.equals("0")) 
                dic.showSection("WAITING");            
            else if (status.equals("1"))
                dic.showSection("POST_ACTIVE");            
            else if(status.equals("2"))
                dic.showSection("POST_INACTIVE");
            
            int count = lstPostData.size();
            String pageNavi = CommonUtil.getPageNavi(page, count, POST_PER_PAGE, "?" + req.getQueryString());
            dic.setVariable("PAGENAVI", pageNavi);
            
            Template template = RenderModel.getAdminCTemplate("post_profile_list");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("AdminPostController.renderSearchPage: " + ex.getMessage(), ex);
        }
        return content;
    }
    
    
    
    private String renderEditPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
            if (!CommonUtil.checkAccess(req, UserRole.POST_VIEW) && !CommonUtil.checkAccess(req, UserRole.POST_EDIT)) {
                return CommonUtil.toPermissionDenied();
            }

            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req));
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "postedit"));
            dic.setVariable("PAGE_TITLE", "Cập nhật tin tức");
            dic.showSection("EDIT_PAGE");

            if (CommonUtil.checkAccess(req, UserRole.POST_EDIT)) {
                dic.showSection("POST_EDIT");                    
            }
            if(CommonUtil.checkAccess(req, UserRole.POST_PUBLIC)){
                dic.showSection("OP_PUBLISH");
            }
            
            String id = req.getParameter("id") != null ? req.getParameter("id") : "";
            if (id.isEmpty()) {
                resp.sendRedirect("/post");
                return "";
            }
            
            String pId = req.getParameter("pid") != null ? req.getParameter("pid") : "";            
            if(!pId.equals(""))
            {
                dic.showSection("PROFILE_BACK");
                dic.setVariable("POST_PID", pId);                                
            }
            ProfileModel profileModel = ProfileModel.getInstance();
            dic.setVariable("PROFILE_LIST", profileModel.getProfileList());

            PostModel postModel = PostModel.getInstance();
            PostData postData = postModel.getPostById(id);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            if (postData != null) {
                //dic.setVariable("POST_PID", postData.getPid());
                dic.setVariable("POST_ID", postData.getId());
                dic.setVariable("POST_TITLE", postData.getTitle());
                if (postData.getStatus() == 0) {
                    dic.showSection("WAITING");
                } else if (postData.getStatus() == 1){
                    dic.showSection("POST_ACTIVE");
                }
                else dic.showSection("POST_INACTIVE");
                dic.setVariable("POST_SOURCE", postData.getSite());  
                Date d = new Date(postData.getPublished());
                String time = sdf.format(d);
                dic.setVariable("POST_TIME", time);
                String image = postData.getThumbFb();
                if (image.isEmpty()) {
                    dic.showSection("NO_THUMB");
                } else {
                    dic.showSection("HAS_THUMB");
                    Date date = new Date(postData.getCreated());
                    String timeDir = (date.getYear() + 1900) + "_" + (date.getMonth() + 1);
                    dic.setVariable("IMAGE_SRC", STATIC_URL_IMAGE + timeDir + "/" + image);
                    dic.setVariable("IMAGE_NAME", image);
                }                
                
                NewsCateModel newsCateModel = NewsCateModel.getInstance();
                List<NewsCateData> listNewsCate = newsCateModel.getCate(0, -1);
                if (listNewsCate != null && !listNewsCate.isEmpty()) {
                    Re_Post_NewsCate_Model modelRe = Re_Post_NewsCate_Model.getInstance();
                    List<Re_Post_NewsCate_Data> listOfCurrentPost = modelRe.getItemsByPostId(id);
                    for (NewsCateData cateData : listNewsCate) {
                        TemplateDataDictionary section = dic.addSection("NEWSCATE_LIST");
                        section.setVariable("NEWSCATE_ID", String.valueOf(cateData.getId()));
                        section.setVariable("NEWSCATE_NAME", cateData.getName());
                        //show cate checked
                        for(Re_Post_NewsCate_Data dt : listOfCurrentPost){
                            if(dt.getIdNewsCate().equals(cateData.getId()))
                                section.showSection("CATE_CHECKED");
                        }
                    }
                }                
                dic.setVariable("POST_DESC", postData.getDesc());                
                dic.setVariable("POST_SLUG", postData.getSlug());
                
                Re_Post_Profile_Model modelRe = Re_Post_Profile_Model.getInstance();
                List<Re_Post_Profile_Data> listProfileOfPost = modelRe.getItemsByPostId(id);
                for(Re_Post_Profile_Data dt : listProfileOfPost){
                    ProfileData profileData = profileModel.getProfileById(dt.getIdProfile());
                    if(profileData != null){
                        TemplateDataDictionary section = dic.addSection("PROFILE_SELECTED");
                        section.setVariable("PROFILE_ID", String.valueOf(profileData.getId()));
                        section.setVariable("PROFILE_NAME", profileData.getName());
                    }                    
                }
                
                dic.setVariable("POST_CONTENT", postData.getContent());  
                dic.showSection("UPDATE_INFO");
                dic.setVariable("POST_EDITOR", postData.getEditor());
                dic.setVariable("POST_AUTHOR", postData.getAuthor());
                dic.setVariable("POST_STATUS", String.valueOf(postData.getStatus()));
                String updated = formatter.format(postData.getUpdated());
                String created = formatter.format(postData.getCreated());
                dic.setVariable("POST_UPDATED", updated);
                dic.setVariable("POST_CREATED", created);
                                                               
                Template template = RenderModel.getAdminCTemplate("post_add");
                content = template.renderToString(dic);
            } else {
                resp.sendRedirect("/post");
                return "";
            }
        } catch (Exception ex) {
            logger.error("AppsController.renderEditPage: " + ex.getMessage(), ex);
        }
        return content;
    }

    private String ajaxEdit(HttpServletRequest req, HttpServletResponse resp) {
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
        if (!CommonUtil.checkAccess(req, UserRole.POST_EDIT)) {
            return CommonUtil.toPermissionDenied();
        }

        String content;
        int error = 0;
        String msg = "Cập nhật tin tức thành công.";
        Map<String, String> data = new HashMap<>();
        try {             
            String postId = "";
            String title = "";
            String slug = CommonUtil.URLFriendly(title);
            String desc = "";
            String scontent = "";
            long time = 0;
            String status = "0";
            String source = "";
            String image = "";
            List<String> lstCats = new ArrayList<>();
            List<String> lstProfile = new ArrayList<>();            
            String imageOld = "";
            FileItem fileImage = null;
            
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(repository);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(req);

            Iterator<FileItem> iter = items.iterator();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            while (iter.hasNext()) {
                FileItem item = iter.next();
                String name = item.getFieldName();
                if (item.isFormField()) {
                    String value = item.getString("UTF-8");
                    switch (name) {
                        case "postId":
                            postId = value;
                            break;                            
                        case "postTitle":
                            title = value;
                            break;
                        case "postStatus":
                            status = value;
//                            if(value.equalsIgnoreCase("1"))
//                                status = "0";
                            break; 
                        case "postSource":
                            source = value;
                            break;    
                        case "postTime":
                            if (!value.isEmpty()) {
                                if(value.length() == 10)
                                    value = value + " 00:00";
                                Date date = sdf.parse(value);
                                time = date.getTime();
                            }
                            else
                                time = System.currentTimeMillis();
                            break;
                        case "imageOld":
                            imageOld = value;
                            break;                            
                        case "newsCate":
                            lstCats.add(value);
                            break;   
                        case "postDesc":
                            desc = value;
                            break;
                        case "postContent":
                            scontent = value;
                            break;                          
                        case "postListProfile":
                            lstProfile = Arrays.asList(value.split("\\s*,\\s*"));
                            break;    
                    }
                } 
                else {
                    if (name.equalsIgnoreCase("newsImage")) {
                        String fileName = item.getName();
                        String contentType = item.getContentType();
                        if (!contentType.startsWith("image/")) {
                            msg = "Chỉ được phép upload hình jpg, png, gif.";
                            error = -1;
                        }
                        long sizeInBytes = item.getSize();
                        if (sizeInBytes > 1024 * 1000) {
                            msg = "Kích thước tối đa 1 MB.";
                            error = -1;
                        }
                        image = (System.currentTimeMillis() / 1000) + "_" + fileName.toLowerCase();
                        image = image.substring(0, image.length() - 4) + ".jpg";
                        fileImage = item;
                    }
                }
            }
            
            if (title.equalsIgnoreCase("")) {
                msg = "Tiêu đề tin tức không được trống.";
                error = -1;
            }
            if(lstCats.isEmpty()){
                msg = "Chưa chọn danh mục.";
                error = -1;
            }
            
            if (error == 0) {
                SessionModel sessionModel = SessionModel.getInstance();                
                String author = sessionModel.getUserLogin(req);
                PostModel postModel = PostModel.getInstance();
                PostData postEdit = postModel.getPostById(postId);   
                String titleEdit = postEdit.getTitle();
                image = fileImage == null ? imageOld : image;
                PostData postData = new PostData(postId, title, slug, desc, 
                        scontent, author, Short.parseShort(status), time, source, image);   
                boolean updatePost = postModel.updatePost(postData);
                if (!updatePost) {
                    error = -1;
                    msg = "Có lỗi xảy ra.";
                }
                else{
                    Re_Post_NewsCate_Model modelRe = Re_Post_NewsCate_Model.getInstance();
                    modelRe.deleteItemsByIdPost(postId);
                    for(String cate : lstCats){
                            Re_Post_NewsCate_Data dataRe = new Re_Post_NewsCate_Data(postId, cate);                            
                            modelRe.addItems(dataRe);
                    }        
                    
                    ProfileModel profileModel = ProfileModel.getInstance();
                    Re_Post_Profile_Model modelRe_Post_Profile = Re_Post_Profile_Model.getInstance();
                    modelRe_Post_Profile.deleteItemsByIdPost(postId);
                    for(String item : lstProfile){
                        if(!item.equals("")){
                            ProfileData profileData = profileModel.getProfileById(item);
                            if(profileData != null){
                                Re_Post_Profile_Data dataRe = new Re_Post_Profile_Data(postId, item);
                                modelRe_Post_Profile.addItems(dataRe);
                            }                            
                        }                        
                    }         
                    //data.put("id", String.valueOf(updateNews)); 
                    if(fileImage != null){
                        PostData postUpdated = postModel.getPostById(postId);
                        Date date = new Date(postUpdated.getCreated());
                        String timeDir = (date.getYear() + 1900) + "_" + (date.getMonth() + 1);
                        saveThumb(fileImage, image, timeDir);
                    }                    
                    ActionModel actionModel = ActionModel.getInstance();
                    actionModel.addAction(req, author, ActionType.POST_EDIT, postId, titleEdit);
                }                
            }     
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg, data);
        return content;
    }

    
    
    private String ajaxDelete(HttpServletRequest req, HttpServletResponse resp) {
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
        if (!CommonUtil.checkAccess(req, UserRole.POST_EDIT)) {
            return CommonUtil.toPermissionDenied();
        }

        String content;
        int error = 0;
        String msg = "Xoá Post thành công.";
        try {
            String id = req.getParameter("id") != null ? req.getParameter("id") : "";
            if (id.isEmpty()) {
                msg = "Post Id không được trống.";
                error = -1;
            } else {
                SessionModel sessionModel = SessionModel.getInstance();
                String userLogin = sessionModel.getUserLogin(req);
                PostModel postModel = PostModel.getInstance();
                PostData postData = postModel.getPostById(id);
                String title = postData.getTitle();
                boolean addApps = postModel.deletePost(id);                
                if (!addApps) {
                    msg = "Có lỗi xảy ra.";
                    error = -1;
                }
                else{
                    Date date = new Date(postData.getCreated());
                    String timeDir = (date.getYear() + 1900) + "_" + (date.getMonth() + 1);
                    deleteThumb(postData.getThumbFb(), timeDir);
                    Re_Post_NewsCate_Model modelRe = Re_Post_NewsCate_Model.getInstance();
                    modelRe.deleteItemsByIdPost(id);
                    Re_Post_Profile_Model modelRe_Post_Profile = Re_Post_Profile_Model.getInstance();
                    modelRe_Post_Profile.deleteItemsByIdPost(id);
                    
                    ActionModel actionModel = ActionModel.getInstance();
                    actionModel.addAction(req, userLogin, ActionType.POST_DELETE, id, title);
                }
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg);
        return content;
    }
    
    
    
    private void deleteThumb(String thumbFb, String timeDir) {
        if (thumbFb == null || thumbFb.isEmpty()) {
            return;
        }
        String localPath = STATIC_UPLOAD_IMAGE + timeDir + "/" + thumbFb;
        File file = new File(localPath);
        if (file.exists()) {
            file.delete();
            logger.info("Delete image success");
        }
    }
    
    
    private String ajaxUploadImage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        int error = 0;
        String msg = "Upload hình thành công.";
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
        try {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(repository);
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(req);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();
                if (!item.isFormField()) {
                    String name = item.getFieldName();
                    if (name.equalsIgnoreCase("postImage")) {
                        String fileName = item.getName();
                        String contentType = item.getContentType();
                        if (!contentType.startsWith("image/")) {
                            msg = "Chỉ được phép upload hình jpg, png, gif.";
                            error = -1;
                        }
                        long sizeInBytes = item.getSize();
                        if (sizeInBytes > 1024 * 1000) {
                            msg = "Kích thước tối đa 1 MB.";
                            error = -1;
                        }
                        String postImage = System.currentTimeMillis() + "_" + fileName.toLowerCase();
                        // crop and resize
                        if (item != null) {
                            Image image = new Image(item.get());
                            BufferedImage bi = image.getBufferedImage();
                            if (!postImage.endsWith(".jpg")) {
                                bi = CommonUtil.convertPNGToJPG(bi);
                            }
                            String localPath = STATIC_UPLOAD_IMAGE + postImage;
                            //String remotePath = REMOTE_POST_PATH + postImage;
                            File uploadedFile = new File(localPath);
                            ImageIO.write(bi, "jpg", uploadedFile);
                            // put to FTP 
                            //CommonUtil.putImageToFTP(localPath, remotePath);
                            postImage = STATIC_URL_IMAGE + postImage;
                            content = "<script>top.$('.mce-btn.mce-open').parent().find('.mce-textbox').val('" + postImage + "').closest('.mce-window').find('.mce-primary').click();</script>";
                        }
                    }
                }
            }
            if (error == 0) {

            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
//        content = CommonModel.toJSON(error, msg, data);
        return content;
    }
}
